package com.online.shopping.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.online.shopping.mapper.TbContentCategoryMapper;
import com.online.shopping.pojo.*;
import com.online.shopping.service.ContentService;
import io.minio.MinioClient;
import io.minio.policy.PolicyType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Rui
 * @version 1.0
 * @date 2020/11/16 13:26
 */
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/manager/content")
public class ContentController {

    @Autowired
    private ContentService contentService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${minio.endpoint}") // http://localhost:9000 #minio服务所在地址
    private String endpoint;
    @Value("${minio.bucketName}")   // mall #存储桶名称
    private String bucketName;
    @Value("${minio.accessKey}")    // minioadmin #访问的key
    private String accessKey;
    @Value("${minio.secretKey}")    // minioadmin #访问的密匙
    private String secretKey;

    /**
     * 添加首页广告
     * @param content
     */
    @PostMapping("/addAd")
    public CommonResult addAd(@RequestBody TbContent content){
        try {
            contentService.addContent(content);
            redisTemplate.boundHashOps("content").delete(content.getCategoryId());
            return new CommonResult(200, "添加成功！", content);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "添加失败！");
        }
    }

    /**
     * 更新首页广告
     * @param content
     */
    @PostMapping("/updateAd")
    public void updateAd(@RequestBody TbContent content){
        TbContent oldContent = contentService.findContentById(content.getId());
        // 清除之前分类的广告缓存
        redisTemplate.boundHashOps("content").delete(oldContent.getCategoryId());
        contentService.updateContent(content);
        // 清除缓存
        if (!content.getCategoryId().equals(oldContent.getCategoryId())){
            redisTemplate.boundHashOps("content").delete(content.getCategoryId());
        }
    }

    @GetMapping("/findByCategoryId")
    public List<TbContent> findByCategoryId(Long categoryId){
        // 加入缓存的代码
        List<TbContent> list = (List<TbContent>) redisTemplate.boundHashOps("content").get(categoryId);
        if (list == null){
            log.info("*****查询数据库*****");
            TbContentExample example = new TbContentExample();
            TbContentExample.Criteria criteria = example.createCriteria();
            // 有效广告
            criteria.andStatusEqualTo("1");

            criteria.andCategoryIdEqualTo(categoryId);
            //排序
            example.setOrderByClause("sort_order");

            list = contentService.selectByExample(example);

            redisTemplate.boundHashOps("content").put(categoryId, list);
        }else {
            log.info("*****从缓存中获取*****");
        }
        return list;
    }

    @PostMapping("/uploadFile")
    @CrossOrigin("*")   // 跨域访问
    public CommonResult uploadFile(MultipartFile file){
        try {
            MinioClient minioClient = new MinioClient(endpoint, accessKey, secretKey);
            boolean isExist = minioClient.bucketExists(bucketName);

            if (!isExist){
                minioClient.makeBucket(bucketName);
                minioClient.setBucketPolicy(bucketName, "*.*", PolicyType.READ_ONLY);
            }

            // 设置存储对象名称
            String fileName = file.getOriginalFilename();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String objectName = sdf.format(new Date()) + "/" + fileName;

            // 把存储对象上传至服务器中
            minioClient.putObject(bucketName, objectName, file.getInputStream(), file.getContentType());
            System.out.println("文件上传成功");

            String objectUrl = minioClient.getObjectUrl(bucketName, objectName);
            System.out.println(objectUrl);

            return new CommonResult(200, "上传成功！", objectUrl);

        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "上传失败！");
        }
    }

    @GetMapping("/findAllContent")
    public List<TbContent> findAllContent(){
        List<TbContent> contents = contentService.findAllContent();
        log.info(String.valueOf(contents));
        return contents;
    }

    @GetMapping("/findContentById/{id}")
    public TbContent findContentById(@PathVariable("id") Long id){
        TbContent content = contentService.findContentById(id);
        log.info(String.valueOf(content));
        return content;
    }

    @PostMapping("/addContent")
    public CommonResult addContent(@RequestBody TbContent content){
        try {
            contentService.addContent(content);
            redisTemplate.boundHashOps("content").delete(content.getCategoryId());
            return new CommonResult(200, "添加成功！", content);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "添加失败！");
        }
    }

    @PostMapping("/updateContent")
    public CommonResult updateContent(@RequestBody TbContent content){
        try {
            System.out.println(content);
            contentService.updateContent(content);
            redisTemplate.boundHashOps("content").delete(content.getCategoryId());
            return new CommonResult(200, "修改成功！", content);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "修改失败！",content);
        }
    }

    @GetMapping("/delContent/{id}")
    public CommonResult delContent(@PathVariable("id") Long id){
        try {
            TbContent content = contentService.findContentById(id);
            System.out.println(content);
            redisTemplate.boundHashOps("content").delete(content.getCategoryId());
            contentService.delContent(id);
            return new CommonResult(200, "删除成功！", id);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "删除失败！");
        }
    }

    @GetMapping("/delManyContents")
    public CommonResult delManyContents(Long[] ids){
        try {
            contentService.delManyContents(ids);
            return new CommonResult(200, "删除成功！", ids);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "删除失败！");
        }
    }

    @GetMapping("/openManyContents")
    public CommonResult openManyContents(Long[] ids){
        try {
            for (Long id : ids) {
                TbContent content = contentService.findContentById(id);
                content.setStatus("1");
                contentService.updateContent(content);
                log.info(String.valueOf(content));
            }
            return new CommonResult(200, "开启成功！", ids);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "开启失败！");
        }
    }

    @GetMapping("/closeManyContents")
    public CommonResult closeManyContents(Long[] ids){
        try {
            for (Long id : ids) {
                TbContent content = contentService.findContentById(id);
                content.setStatus("0");
                contentService.updateContent(content);
                log.info(String.valueOf(content));
            }
            return new CommonResult(200, "屏蔽成功！", ids);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "屏蔽失败！");
        }
    }

    @GetMapping("/findByPage")
    public ResultPage findByPage(int pageNum, int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        Page<TbContent> page = (Page<TbContent>) contentService.findAllContent();

        ResultPage resultPage = new ResultPage();
        resultPage.setRows(page.getResult());
        resultPage.setTotal(page.getTotal());

        return resultPage;
    }

    // 查找广告分类
    @Autowired
    private TbContentCategoryMapper contentCategoryMapper;
    @GetMapping("/findAllContentCategories")
    public List<TbContentCategory> findAllContentCategories(){
        List<TbContentCategory> tbContentCategories = contentCategoryMapper.selectByExample(null);
        log.info(String.valueOf(tbContentCategories));
        return tbContentCategories;
    }

}
